﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NAnt.Core;

namespace NAntExt.Tasks
{
    /// <summary>
    /// Extensions for <see cref="NAnt.Core.Task"/>.
    /// </summary>
    public static class TaskExtensions
    {
        /// <summary>
        /// Throws or logs the exception thrown based on whether the <c>FailOnError</c>
        /// property has been set to <c>true</c> or <c>false</c>
        /// </summary>
        /// <param name="task">The instance to extend.</param>
        /// <param name="location">The location of the task.</param>
        /// <param name="ex">The exception to handle.</param>
        public static void ThrowOrLog(this Task task, Location location, Exception ex)
        {
#if DEBUG
            System.Diagnostics.Debug.WriteLine(ex, "Error");
#endif

            string errorMessage;
            if (ex == null)
                errorMessage = "null";
            else
                if (task.Verbose)
                    errorMessage = ex.ToString();
                else
                    errorMessage = ex.Message;

            if (task.FailOnError)
                throw new BuildException("Task failed during execution due to an unhanled exception.", location, ex);
            else
                task.Log(Level.Error, "Error: Task failed during execution due to an unhanled exception. Exception = {0}", errorMessage);
        }

    }
}
